/*
Technically, the React import is not required in all React projects as you learned. But you're never wrong with
adding it.
 */
import React, {Fragment, useState} from 'react';
import Card from "../UI/Card.ui";
import ButtonUi from "../UI/Button.ui";
import ErrorModal from "../UI/ErrorModal.ui";
import classes from './AddUser.module.css';

const AddUser = ({onAddUser}) => {
    const [enteredUsername, setEnteredUsername] = useState('');
    const [enteredAge, setEnteredAge] = useState('');
    const [error, setError] = useState(null);

    const addUserHandler = (event) => {
        event.preventDefault();
        if (enteredUsername.trim().length === 0 || enteredAge.trim().length === 0) {
            setError( {
                title: 'Invalid Input',
                message: 'Please enter a valid name and age (non-empty values).'
            });
            return;
        }

        if (+enteredAge < 1) {
            setError( {
                title: 'Invalid Age',
                message: 'Please enter a valid age (> 0).'
            });
            return;
        }
        onAddUser(enteredUsername, enteredAge);
        setEnteredUsername('');
        setEnteredAge('');
    }

    const usernameChangeHandler = (event) => {
        setEnteredUsername(event.target.value);
    }

    const ageChangeHandler = (event) => {
        setEnteredAge(event.target.value);
    }

    const errorHandler = () => {
        setError(null);
    }

    return (
        <Fragment>
            {error && <ErrorModal title={error.title} message={error.message} onConfirm={errorHandler} />}
            <Card className={classes.input}>
                <form onSubmit={addUserHandler}>
                    <label htmlFor="username">Username</label>
                    <input id="username" type="text"
                           value={enteredUsername}
                           onChange={usernameChangeHandler} />
                    <label htmlFor="age">Age (Years)</label>
                    <input id="age" type="text"
                           value={enteredAge}
                           onChange={ageChangeHandler} />
                    <ButtonUi type="submit">Add User</ButtonUi>
                </form>
            </Card>
        </Fragment>
    )
};

export default AddUser;
